// pages/search/search.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSimilar: false,
    lowPrice: '', // 删选最低价
    highPrice: '', // 删选最高价
    init: true, // 是否为初始化状态(显示搜索记录)
    histories: [], // 需要清空数组
    hotKeywords: [], // 需要清空数组
    keyword: '',
    priceOpposite: true,
    countOpposite: true,
    priceFocus: false,
    countFocus: false,
    scrollHeight: '',
    reorderName: '',
    panelHidden: true, //筛选面板隐藏标识
    startX: 0, //开始坐标
    startY: 0,
    searchResults: [],
    contentFound: false, //是否有搜索内容
    filterItems: [{
        name: 'USA',
        value: '美国'
      },
      {
        name: 'CHN',
        value: '中国',
        checked: 'true'
      },
      {
        name: 'BRA',
        value: '巴西'
      },
      {
        name: 'JPN',
        value: '日本'
      },
      {
        name: 'ENG',
        value: '英国'
      },
      {
        name: 'TUR',
        value: '法国'
      },
    ],
    page: 1,
    type: 0,
    isEnd: false,
    toggle: true,
    partData: {
      imgUrls: '',
      name: '',
      inventory: 0,
      price: '',
      goods_id: '',
      detail: false
    },
  },

  toDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`,
    })
  },

  // 获取表单输入内容
  changeInputContent(e) {
    const that = this;
    that.setData({
      keyword: e.detail.value
    })
  },

  // 筛选复选框
  checkboxChange(e) {
    console.log(e.detail.value)
    const that = this;
    for (let i = 0; i < that.data.filterItems.length; i++) {
      if (e.detail.value.indexOf(that.data.filterItems[i].name) != -1) {
        that.data.filterItems[i].checked = true;
      } else {
        that.data.filterItems[i].checked = false;
      }
    }
    that.setData({
      filterItems: that.data.filterItems
    })
  },

  // 表单聚焦回到初始状态
  bindfocus() {
    const that = this;
    that.setData({
      init: true
    })
  },

  // 排序事件
  getTotalList() {
    const that = this;
    that.getData();
    that.setData({
      reorderName: "综合", //当前样式判断根据
      countFocus: false,
      priceFocus: false,
      lowPrice: '',
      highPrice: '',
      isEnd: false,
      p: 1
    })
  },
  getCountList() {
    const that = this;
    // that.getData('sales_sum', 'asc');
    that.setData({
      reorderName: "销量", //当前样式判断根据
      countOpposite: !that.data.countOpposite, //价格排序判断根据
      countFocus: true,
      priceFocus: false,
      isEnd: false,
      lowPrice: '',
      highPrice: '',
      p: 1
    })
    that.data.countOpposite ? that.getData('sales_sum', 'asc') : that.getData('sales_sum', 'desc')

  },
  getPriceList() {
    const that = this;

    that.setData({
      reorderName: "价格", //当前样式判断根据
      priceOpposite: !that.data.priceOpposite, //价格排序判断根据
      priceFocus: true,
      countFocus: false,
      lowPrice: '',
      highPrice: '',
      isEnd: false,
      p: 1
    })
    that.data.priceOpposite ? that.getData('shop_price', 'asc') : that.getData('shop_price', 'desc')
  },
  getFilterList() {
    const that = this;
    that.setData({
      reorderName: "筛选", //当前样式判断根据
      priceFocus: false,
      countFocus: false,
      panelHidden: false,
      lowPrice: '',
      highPrice: '',
      isEnd: false,
      p: 1
    })
  },

  // 隐藏筛选面板
  hidePanel() {
    const that = this;
    that.setData({
      panelHidden: true
    });
  },

  touchstart(e) {
    const that = this;
    that.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
    })
  },
  /**
   * 滑动事件处理
   */
  touchmove(e) {
    const that = this;
    let startX = that.data.startX; //开始X坐标
    let startY = that.data.startY; //开始Y坐标
    let touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标
    let touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标
    //获取滑动角度
    let angle = that.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    });
    if (Math.abs(angle) > 30) return;
    if (touchMoveX - startX > 30) {
      that.hidePanel();
    }
  },
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  getData(sort = '', sort_asc = '', start_price = '', end_price = '') {
    const that = this;
    that.setData({
      page: 1
    })
    let json = {
      q: that.data.keyword,
      sort: sort,
      sort_asc,
      start_price,
      end_price,
      p: that.data.page,
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.search, jsonData).then(res => { // 根据搜索词从数据库获取数据
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (!res.result.goods_list.length) { //返回空数据
          // 显示未找到内容页面
          that.setData({
            init: false,
            contentFound: false
          })
        } else {
          if (that.data.histories.indexOf(that.data.keyword) == -1) {
            that.data.histories.push(that.data.keyword);
          }
          that.setData({
            init: false,
            contentFound: true,
            searchResults: app.getImg(res.result.goods_list),
            histories: that.data.histories
          })
          app.utils.mySetStorage('histories', that.data.histories);
        }
      } else {
        throw res.msg
      }

    }).catch(err => {
      app.showInfo(err.toString())
    })
  },

  changeLow(e) {
    const that = this;
    that.setData({
      lowPrice: e.detail.value
    })
  },
  changeHigh(e) {
    const that = this;
    that.setData({
      highPrice: e.detail.value
    })
  },

  // 提交搜索
  searchSubmit() {
    const that = this;
    if (that.data.keyword == '') { //判断内容是否为空
      app.showInfo('内容不能为空');
    } else {
      that.getData();
    }
  },

  // 历史标签快捷搜索
  fastSearchHistory(e) {
    const that = this;
    let index = e.target.dataset.index;
    if (e.target.dataset.index != undefined) {
      that.setData({
        keyword: that.data.histories[index]
      })
      that.searchSubmit();
    }
  },

  // 热搜标签快捷搜索
  fastSearchHot(e) {
    const that = this;
    let index = e.target.dataset.index;
    if (e.target.dataset.index != undefined) {
      that.setData({
        keyword: that.data.hotKeywords[index]
      })
      that.searchSubmit();
    }
  },

  //筛选提交
  filterSubmit() {
    const that = this;
    that.getData('', '', that.data.lowPrice, that.data.highPrice);
    that.setData({
      panelHidden: true
    })
  },


  // 删除历史记录
  deleteHistory() {
    const that = this;
    wx.showModal({
      title: '',
      content: '确认删除全部历史记录',
      confirmText: '删除',
      confirmColor: '#ff5151',
      success(res) {
        if (res.confirm) {
          that.setData({
            hiddenLoading: false
          })
          wx.removeStorageSync('histories');
          setTimeout(() => {
            that.setData({
              histories: [],
              hiddenLoading: true
            })
          }, 400)
        } else {
          console.log('取消删除')
        }
      }
    })
  },
  // 触底加载
  toupper(e) {
    const that = this;
    let pages = that.data.page;
    pages++;
    let parme = {}
    if (that.data.countFocus) {
      parme = {
        sort: 'sales_sum',
        sort_asc: that.data.countOpposite ? 'asc' : 'desc',
        start_price: '',
        end_price: ''
      }
    } else if (that.data.priceFocus) {
      parme = {
        sort: 'shop_price',
        sort_asc: that.data.priceOpposite ? 'asc' : 'desc',
        start_price: '',
        end_price: ''
      }
    } else {
      parme = {
        sort: '',
        sort_asc: '',
        start_price: that.data.lowPrice,
        end_price: that.data.highPrice
      }
    }

    let json = {
      q: that.data.keyword,
      store_id: app.globalData.address.select_store_id,
      sort: parme.sort,
      sort_asc: parme.sort_asc,
      start_price: parme.start_price,
      end_price: parme.end_price,
      p: pages,
      crd_store_id: app.globalData.nextdayStore ? app.globalData.nextdayStore : '0'
    }
    console.log(json)
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.search, jsonData).then(res => { // 根据搜索词从数据库获取数据
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (that.data.histories.indexOf(that.data.keyword) == -1) {
          that.data.histories.push(that.data.keyword);
        }
        let data = that.data.searchResults;
        if (res.result.goods_list.length == 0) {
          that.setData({
            isEnd: true
          })
        } else {
          res.result.goods_list.forEach(res => {
            data.push(res)
          })
          that.setData({
            init: false,
            contentFound: true,
            searchResults: app.getImg(data),
            histories: that.data.histories,
            page: pages
          })
          app.utils.mySetStorage('histories', that.data.histories);
        }

      } else {
        throw res.msg
      }

    })
  },
  // 点击添加购物车
  addShowCart(e) {
    const that = this;
    let goods = e.currentTarget.dataset.goods
    that.setData({
      toggle: false,
      'partData.imgUrls': goods.img,
      'partData.name': goods.goods_name,
      'partData.inventory': goods.store_count,
      'partData.price': goods.shop_price,
      'partData.goods_id': goods.goods_id,
    })
  },
  // 添加到购物车
  addToCart(e) {

    app.checkUserInfoAuthorizationCart().then(() => {
      const that = this;
      let token = app.globalData.token;
      let json = {
        token,
        goods_num: e.detail,
        goods_id: that.data.partData.goods_id,
      }
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.addCart, jsonData).then(res => {
        if (res.status == 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 2000
          })
          app.getCartCount();
          app.cartCountCallback = (res) => {
            that.setData({
              cartCount: res
            })
          }
        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
      })

    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    let systemInfo = wx.getSystemInfoSync();
    //获取scroll高度
    if (options.where == "similar") {
      wx.setNavigationBarTitle({
        title: '相似商品',
      })
      that.setData({
        windowHeight: systemInfo.windowHeight,
        windowWidth: systemInfo.windowWidth,
        scrollHeight: systemInfo.windowHeight,
        isSimilar: true
      })
      let json = {
        id: options.id
      }
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.getSimilar, jsonData).then(res => {
        that.setData({
          hiddenLoading: true
        })
        if (res.status == 1) {
          app.getImg(res.result);
          if (res.result.length == 0) {
            that.setData({
              searchResults: res.result,
              contentFound: false,
              init: false
            })
          } else {
            that.setData({
              searchResults: res.result,
              contentFound: true,
              init: false
            })
          }
        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString());
        that.setData({
          hiddenLoading: true
        })
      })
    } else {

      that.setData({
        windowHeight: systemInfo.windowHeight,
        windowWidth: systemInfo.windowWidth,
        scrollHeight: systemInfo.windowHeight - 160 / 750 * app.globalData.systemInfo.windowWidth
      })
      // 从本地存储获取历史搜索词
      let histories = wx.getStorageSync("histories");
      let json = {}
      app.utils.post(app.api.reqUrls.getConfig, app.utils.getSignData(json)).then(res => {
        that.setData({
          hiddenLoading: true
        })
        if (res.status == 1) {
          let arr = res.result.config.filter(item => {
            return item.name == "hot_keywords"
          })
          let hotKeywords = arr[0].value.split("|");
          that.setData({
            histories: histories.length ? histories : [],
            hotKeywords
          })
        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
      })

    }
    // 判断是否渠道会员，type == 1是渠道会员
    // app.getInfo(app.globalData.token, () => {
    //   console.log(app.globalData.userInfo)
    //   if (app.globalData.userInfo) {
    //     that.setData({
    //       type: app.globalData.userInfo.type
    //     })
    //   } else {
    that.setData({
      type: 0
    })
    //   }
    // })
  },
  onShow: function () {
    //数据统计
    app.statistics("page/detail/pages/search/search", "搜索")
  }
})